package com.fmx.BookStore.controller;

import com.fmx.BookStore.core.domain.AjaxResult;
import com.fmx.BookStore.domain.User;
import com.fmx.BookStore.vo.UserRequest;
import com.fmx.BookStore.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @GetMapping(value = "/{userId}")
    @ApiOperation("根据ID找用户")
    public AjaxResult selectUserById(@PathVariable("userId") Long userId){
        return AjaxResult.success(userService.selectUserById(userId));
    }
    @GetMapping("/list")
    @ApiOperation("根据其他信息查询用户")
    public AjaxResult listUser(User user){
        List<User> list = userService.listUser(user);
        return AjaxResult.success(list);
    }

    @PostMapping
    @ApiOperation("新增用户")
    public AjaxResult addUser(@RequestBody User user){
        int rows = userService.insertUser(user);
        return rows > 0 ? AjaxResult.success("添加用户成功") : AjaxResult.error("添加用户失败");
    }

    @PutMapping
    @ApiOperation("修改用户信息")
    public AjaxResult updateUser(@RequestBody User user){
        int rows = userService.updateUser(user);
        return rows > 0 ? AjaxResult.success("修改用户成功") : AjaxResult.error("修改用户失败");
    }

    @DeleteMapping("/{userId}")
    @ApiOperation("删除用户")
    public AjaxResult deleteUser(@PathVariable Long userId){
        int rows = userService.deleteUser(userId);
        return rows > 0 ? AjaxResult.success("删除用户成功") : AjaxResult.error("删除用户失败");
    }

    @GetMapping("/page")
    @ApiOperation("分页操作")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, User user){
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userService.listUser(user);
        PageInfo<List> pageInfo = new PageInfo(list);
        return AjaxResult.success(pageInfo);
    }

    @PostMapping("/login")
    @ApiOperation("登录操作")
    public AjaxResult login(@RequestBody UserRequest userRequest){
        UserRequest temp = userService.login(userRequest);
        User user = new User();
        user.setUserName(temp.getUserName());
        user.setPassword(temp.getPassword());
        List<User> row = userService.listUser(user);
        return row.size()>0 ? AjaxResult.success("登录成功",temp): AjaxResult.error("登录失败");
    }

    @PostMapping("/register")
    @ApiOperation("注册操作")
    public AjaxResult register(@RequestBody UserRequest userRequest){
        return userService.register(userRequest)>0 ?AjaxResult.success("注册成功",userService.register(userRequest)):AjaxResult.error("注册失败");
    }

}
